<template>
  <div class="chat-box">
    <div class="chat-button" @click="toggleDrawer">
        <svg-icon icon-class="chat_ai"></svg-icon>
    </div>
    <el-drawer :visible.sync="drawerVisible" direction="rtl" :size="drawerWidth" :modal="false" :show-close="false"
      custom-class="chat-drawer" @click.native="handleClickOutside">
      <template slot="title" class="chat-title-box">ESOHA 智能助手</template>
      <div class="resize-handle" @mousedown="startResize"></div>
      <div class="chat-container">
        <div class="chat-header">
          <el-button type="text" class="clear-button" @click="clearHistory" :disabled="messages.length === 0">
            <i class="el-icon-delete"></i>
          </el-button>
        </div>
        <div class="message-list">
          <div v-for="(msg, index) in messages" :key="index" :class="['message-item', msg.role]">
            <div class="message-content" @dblclick="copyMessage(msg.content)">
              <div v-html="formatMessage(msg.content)"></div>
              <transition name="fade">
                <div v-if="msg.copied" class="copy-indicator">已复制</div>
              </transition>
            </div>
          </div>
        </div>
        <div class="input-area">
          <el-input v-model="inputMessage" placeholder="输入消息..." @keyup.enter.native="sendMessage"
            @keydown.enter.prevent="handleenter" />
          <el-button type="primary" @click="sendMessage" :loading="isSending" class="send-button">
            发送
          </el-button>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import DOMPurify from 'dompurify'
import hljs from 'highlight.js'
import 'highlight.js/styles/github-dark-dimmed.css'
import settings from '@/settings'
export default {
  mounted() {
    // Initialize highlight.js
    document.querySelectorAll('.code-block pre code').forEach((block) => {
      hljs.highlightBlock(block)
    })
  },
  updated() {
    // Re-run highlight.js after updates
    document.querySelectorAll('.code-block pre code').forEach((block) => {
      hljs.highlightBlock(block)
    })
  },
  data() {
    return {
      modField: null,
      extraFields: {},
      roles: [],
      drawerVisible: false,
      inputMessage: '',
      messages: [],
      isSending: false,
      drawerWidth: '20%',
      isResizing: false,
      startX: 0,
      startWidth: 0
    }
  },
  created() {
    // 获取模型参数
    sa.ajax('/mod/getByCode', {
      code: settings.mod_field
    }, function (res) {
      this.modField = res.data
      if (this.modField.extraFields) {
        for (const fd of JSON.parse(this.modField.extraFields)) {
          const key = fd['key']
          const val = fd['val']
          if (key == 'system' || key === 'assistant') {
            this.roles.push(fd)
          } else {
            this.extraFields[key] = val
          }
        }
      }
    }.bind(this), {
      type: 'get'
    });
  },
  methods: {
    /**
     * 复制消息内容到剪贴板
     * @param {string} content - 要复制的消息内容
     * @returns {void}
     */
    copyMessage(content) {
      navigator.clipboard.writeText(content).then(() => {
        const msg = this.messages.find(m => m.content === content)
        if (msg) {
          this.$set(msg, 'copied', true)
          setTimeout(() => {
            this.$set(msg, 'copied', false)
          }, 2000)
        }
      }).catch(err => {
        console.error('复制失败:', err)
        this.$message.error('复制失败')
      })
    },
    /**
     * 复制代码块内容到剪贴板
     * 当用户点击代码块的复制按钮时触发
     * @param {string} code - 要复制的代码内容
     * @returns {void}
     */
    copyCodeBlock(code) {
      const codeBlock = event.target.closest('.code-block')
      if (codeBlock) {
        const successEl = codeBlock.querySelector('.copy-success')
        if (successEl) {
          successEl.classList.add('show')
          setTimeout(() => {
            successEl.classList.remove('show')
          }, 1000)
        }
      }
      navigator.clipboard.writeText(code).then(() => {
        this.$message.success('代码已复制')
      }).catch(err => {
        console.error('复制失败:', err)
        this.$message.error('复制失败')
      })
    },
    /**
     * 切换代码块的展开/收起状态
     * 当用户点击代码块的切换按钮时触发
     * @param {Event} event - 点击事件对象
     * @returns {void}
     */
    toggleCodeBlock(event) {
      const codeBlock = event.target.closest('.code-block')
      if (codeBlock) {
        codeBlock.classList.toggle('collapsed')
      }
    },
    /**
     * 清空聊天记录
     * 显示确认对话框，用户确认后清空所有消息
     * @returns {void}
     */
    clearHistory() {
      this.$confirm('确定要清空所有聊天记录吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.messages = [];
      }).catch(() => { });
    },
    /**
     * 切换抽屉显示/隐藏状态
     * 控制聊天窗口的展开和收起
     * @returns {void}
     */
    toggleDrawer() {
      this.drawerVisible = !this.drawerVisible
    },
    /**
     * 处理点击抽屉外部区域
     * 当点击抽屉外部区域时关闭抽屉
     * @param {Event} event - 点击事件对象
     * @returns {void}
     */
    handleClickOutside(event) {
      const drawer = this.$el.querySelector('.el-drawer')
      const button = this.$el.querySelector('.chat-button')
      if (drawer && !drawer.contains(event.target) && !button.contains(event.target)) {
        this.drawerVisible = false
      }
    },
    /**
     * 处理回车键按下事件
     * 当用户按下回车键时发送消息
     * @returns {void}
     */
    handleEnter() {
      if (!this.isSending) {
        this.sendMessage()
      }
    },
    /**
     * 开始调整抽屉大小
     * 监听鼠标移动事件，开始调整抽屉宽度
     * @param {MouseEvent} e - 鼠标事件对象
     * @returns {void}
     */
    startResize(e) {
      this.isResizing = true
      this.startX = e.clientX
      this.startWidth = parseInt(this.drawerWidth)
      document.addEventListener('mousemove', this.handleResize)
      document.addEventListener('mouseup', this.stopResize)
    },
    /**
     * 处理调整抽屉大小
     * 根据鼠标移动距离计算并更新抽屉宽度
     * @param {MouseEvent} e - 鼠标事件对象
     * @returns {void}
     */
    handleResize(e) {
      if (!this.isResizing) return
      const deltaX = e.clientX - this.startX
      const newWidth = this.startWidth - (deltaX / window.innerWidth * 100)
      this.drawerWidth = Math.min(Math.max(20, newWidth), 80) + '%'
    },
    /**
     * 停止调整抽屉大小
     * 移除鼠标移动和抬起事件监听器，结束调整过程
     * @returns {void}
     */
    stopResize() {
      this.isResizing = false
      document.removeEventListener('mousemove', this.handleResize)
      document.removeEventListener('mouseup', this.stopResize)
    },
    /**
     * 格式化消息内容，支持Markdown语法
     * 该方法将原始消息内容转换为HTML格式，支持以下功能：
     * 1. 内容安全过滤（使用DOMPurify）
     * 2. Markdown语法解析（包括标题、列表、代码块、表格等）
     * 3. 代码块语法高亮
     * 4. 数学表达式支持
     * 5. 表格对齐支持
     * @param {string} content - 原始消息内容
     * @returns {string} 格式化后的HTML内容
     */
    formatMessage(content) {
      // Sanitize content first
      const sanitized = DOMPurify.sanitize(content, {
        ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'code', 'pre', 'a', 'br', 'ul', 'ol', 'li', 'blockquote', 'table', 'tr', 'th', 'td', 'span', 'div', 'input', 'img', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'details', 'summary'],
        ALLOWED_ATTR: ['href', 'target', 'class', 'style', 'type', 'checked', 'disabled', 'src', 'alt', 'width', 'height', 'open']
      });

      // Enhanced Markdown parsing with better formatting
      let formatted = sanitized
        // Improved numbered list formatting
        .replace(/^(\s*)(\d+)\.\s+(.*)$/gm, (match, indent, num, text) => {
          const level = Math.min(Math.floor(indent.length / 2), 5);
          return `<div class="numbered-item level-${level}">
              <span class="number">${num}.</span>
              <span class="text">${text}</span>
            </div>`;
        })
        // Enhanced list formatting with better spacing and wrapping
        .replace(/^(\s*)(\d+)\.\s+(.*)$/gm, (match, indent, num, text) => {
          const level = Math.min(Math.floor(indent.length / 2), 5);
          return `<div class="numbered-list level-${level}">
              <span class="list-number">${num}.</span>
              <span class="list-text">${text
              .replace(/(\d+)([^\d\s])/g, '$1 $2')
              .replace(/(\d+)/g, '<span class="number">$1</span>')}</span>
            </div>`;
        })
        // Format bullet points with proper spacing and wrapping
        .replace(/^-\s+(.*)$/gm, (match, text) => {
          return `<div class="bullet-list">
              <span class="list-bullet">•</span>
              <span class="list-text">${text
              .replace(/(\d+)([^\d\s])/g, '$1 $2')
              .replace(/(\d+)/g, '<span class="number">$1</span>')
              .replace(/(\d+)([^\d\s])/g, '$1 $2')}</span>
            </div>`;
        })
        // Format quotes with proper styling
        .replace(/^>\s*(.*)$/gm, (match, text) => {
          return `<div class="quote-block">
              <div class="quote-content">${text}</div>
            </div>`;
        })
        // Handle code blocks with language specification and better syntax highlighting
        .replace(/```(\w*)\n([\s\S]*?)```/g, (match, lang, code) => {
          const escapedCode = code
            .replace(/&/g, '&')
            .replace(/</g, '<')
            .replace(/>/g, '>')
            .replace(/"/g, '"')
            .replace(/'/g, '&#039;')
            .trim();
          const languageClass = lang ? `language-${lang}` : '';
          return `<div class="code-block">
              <div class="code-header">
                <span class="lang-tag">${lang || 'text'}</span>
                <div class="code-actions">
                  <span class="copy-btn" onclick="this.parentElement.parentElement.parentElement.__vue__.copyCodeBlock(\`${escapedCode}\`)">
                    <i class="el-icon-document-copy"></i>
                  </span>
                  <span class="toggle-btn" onclick="this.parentElement.parentElement.parentElement.__vue__.toggleCodeBlock(event)">
                    <i class="el-icon-caret-bottom"></i>
                  </span>
                </div>
              </div>
              <pre><code class="hljs ${languageClass}">${escapedCode}</code></pre>
            </div>`;
        })
        // Task lists
        .replace(/^\s*-\s+\[(x| )\]\s+(.*)$/gm, (match, checked, text) => {
          const isChecked = checked.trim().toLowerCase() === 'x';
          return `<div class="task-item">
              <input type="checkbox" ${isChecked ? 'checked' : ''} disabled>
              <span>${text}</span>
            </div>`;
        })
        // Headers
        .replace(/^#{1}\s+(.*)$/gm, '<h1>$1</h1>')
        .replace(/^#{2}\s+(.*)$/gm, '<h2>$1</h2>')
        .replace(/^#{3}\s+(.*)$/gm, '<h3>$1</h3>')
        // Bold and italic
        .replace(/\*\*\*(.*?)\*\*\*/g, '<strong><em>$1</em></strong>')
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        // Code
        .replace(/`(.*?)`/g, '<code>$1</code>')
        // Links and images
        .replace(/!\[(.*?)\]\((.*?)\)/g, '<img src="$2" alt="$1" class="markdown-image" style="max-width:100%;">')
        .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>')
        // Blockquotes
        .replace(/^>\s*(.*)$/gm, '<blockquote>$1</blockquote>')
        // Lists
        .replace(/^\s*-\s+(.*)$/gm, '<li>$1</li>')
        .replace(/^\s*\*\s+(.*)$/gm, '<li>$1</li>')
        .replace(/^\s*\d+\.\s+(.*)$/gm, '<li>$1</li>')
        .replace(/(<li>.*<\/li>)/gs, '<ul>$1</ul>')
        // Horizontal rule
        .replace(/^\s*---\s*$/gm, '<hr>')
        // Line breaks
        .replace(/\n/g, '')
        // Math expressions
        .replace(/\|\|(.*?)\|\|/g, '<span class="math">$1</span>')
        // Enhanced table handling with alignment support
        .replace(/(\|.*\|)\n(\|.*\|)\n((\|.*\|(\n)?)+)/g, (match, header, align, body) => {
          const rows = body.split('\n').filter(row => row.trim());
          const alignments = align.split('|').slice(1, -1).map(col => {
            if (col.startsWith(':') && col.endsWith(':')) return 'center';
            if (col.startsWith(':')) return 'left';
            if (col.endsWith(':')) return 'right';
            return 'left';
          });

          return `<div class="table-container">
              <table>
                <thead>${this.formatTableRow(header, alignments)}</thead>
                <tbody>${rows.map(row => this.formatTableRow(row, alignments)).join('')}</tbody>
              </table>
            </div>`;
        });

      // Add syntax highlighting for code blocks
      if (typeof hljs !== 'undefined') {
        document.querySelectorAll('.code-block pre code').forEach((block) => {
          hljs.highlightBlock(block);
        });
      }

      return formatted;
    },
    /**
     * 格式化表格行
     * 将Markdown表格行转换为HTML表格行，并根据对齐方式设置单元格样式
     * @param {string} row - 原始表格行内容
     * @param {string[]} alignments - 每列的对齐方式数组
     * @returns {string} 格式化后的HTML表格行
     */
    formatTableRow(row, alignments = []) {
      return `<tr>${row
        .split('|')
        .slice(1, -1)
        .map((cell, index) => {
          const alignment = alignments[index] || 'left';
          return `<td style="text-align: ${alignment}">${cell.trim()}</td>`;
        })
        .join('')
        }</tr>`;
    },
    /**
     * 发送消息到DeepSeek API
     * 该方法处理完整的消息发送流程，包括：
     * 1. 验证输入内容是否为空
     * 2. 添加用户消息到消息列表
     *
     * 3. 创建并添加assistant的占位消息
     * 4. 调用DeepSeek API获取流式响应
     * 5. 处理流式响应数据并实时更新消息内容
     * 6. 自动滚动到最新消息
     * 7. 处理各种错误情况并恢复状态
     * 
     * 注意：该方法使用流式API，可以实时显示响应内容
     * 
     * @async
     * @throws {Error} 当API请求失败或响应解析失败时抛出错误
     * @returns {Promise<void>}
     */
    async sendMessage() {
      if (!this.inputMessage.trim()) return

      this.isSending = true
      const userMessage = this.inputMessage

      this.messages.push({
        role: 'user',
        content: userMessage,
        timestamp: new Date().toISOString()
      })

      this.inputMessage = ''

      if (this.roles) {
        for (const rs of this.roles) {
          const msg = {
            role: rs.key,
            content: rs.val || '',
          }
          this.messages.push(msg)
        }
      }
      const messageIndex = this.messages.length - 1
      try {
        const response = await fetch(this.modField['url'], {
          method: this.modField['method'],
          headers: {
            'Content-Type': this.modField['contentType'],
            'Authorization': this.modField['apiKey'],
          },
          body: JSON.stringify({
            messages: this.messages.slice(0, -1).map(msg => ({
              role: msg.role,
              content: msg.content
            })),
            model: this.extraFields['model'],
            temperature: Number(this.extraFields['temperature']),
            max_tokens: Number(this.extraFields['max_tokens']),
            stream: Boolean(this.extraFields['stream'])
          })
        })
        const reader = response.body.getReader()
        if (!reader) {
          throw new Error('Failed to get reader')
        }

        const decoder = new TextDecoder()
        let done = false
        let buffer = ''
        let chunkCount = 0

        while (!done) {
          const {
            value,
            done: streamDone
          } = await reader.read()
          done = streamDone
          if (value) {
            chunkCount++
            const decoded = decoder.decode(value, {
              stream: true
            })
            buffer += decoded
            const lines = buffer.split('\n')
            buffer = lines.pop() || ''

            for (const line of lines) {
              if (!line.startsWith('data: ')) continue

              const data = line.slice(6).trim()
              if (data === '[DONE]') {
                this.messages[messageIndex].isStreaming = false
                break
              }
              try {
                const json = JSON.parse(data)
                const content = json.choices?.[0]?.delta?.content || ''
                if (content) {
                  this.messages[messageIndex].content += content
                  this.$nextTick(() => {
                    const container = this.$el.querySelector('.message-list')
                    if (container) {
                      container.scrollTo({
                        top: container.scrollHeight,
                        behavior: 'smooth'
                      })
                    }
                  })
                }
              } catch (error) {
                if (!buffer.includes('\n')) {
                  buffer = line + '\n' + buffer
                  break
                }
              }
            }
          }
        }
      } catch (error) {
        this.messages.pop()
        this.inputMessage = userMessage
      } finally {
        this.isSending = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '@/styles/mixin.scss';
.chat-box {
  position: fixed;
  z-index: 99;
  right: 0;
  bottom: 120px;
}

.chat-button {
  @include flex-center;
  position: fixed;
  width: 56px;
  height: 56px;
  right: 0;
  bottom: 16%;
  border: 1px solid rgba(0, 0, 0, 0.1);
  border-radius: 50% 0 0 50%;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  transform: translateX(28px);
  backdrop-filter: blur(4px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  &:hover {
    transform: translateX(0) scaleX(1.1);
    background: rgba(255, 255, 255, 1);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    border-color: rgba(0, 0, 0, 0.15);
    &::after {
      opacity: 1;
      transform: scale(1.2);
    }
  }

  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 50% 0 0 50%;
    background: radial-gradient(circle, rgba(0, 179, 255, 0.1) 10%, transparent 10.01%);
    transform: scale(0);
    opacity: 0;
    transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    pointer-events: none;
  }

  .svg-icon {
    width: 24px;
    height: 24px;
    color: #00b3ff;
    transition: color 0.2s;
  }

  &:hover .svg-icon {
    color: #0099cc;
  }
}

.chat-drawer {
  box-shadow: -2px 0 8px rgba(0, 0, 0, 0.05);
  border-radius: 12px 0 0 12px;
  background: #fff;
  padding: 16px 20px;
  margin: 0;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
}

::v-deep .el-drawer__header {
  color: #00b3ff;
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 2px;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-header {
  padding: 12px 20px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: flex-end;
}

.clear-button {
  padding: 0;
  color: #666;
  font-size: 14px;
}

.clear-button:hover {
  color: #ceffef;
}

.message-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  scroll-behavior: smooth;
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.1) transparent;
}

.message-list::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.message-list::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.message-list::-webkit-scrollbar-track {
  background: transparent;
}

.message-item {
  margin-bottom: 20px;
  display: flex;
  align-items: flex-start;
  gap: 16px;

  &.user {
    flex-direction: row-reverse;
  }

  &.assistant {
    flex-direction: row;
  }
}

.message-content {
  display: inline-block;
  padding: 16px 20px;
  margin: 0 16px;
  border-radius: 20px;
  line-height: 1.6;
  font-size: 15px;
  white-space: pre-wrap;
  word-wrap: break-word;
  width: fit-content;
  max-width: 80%;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  box-sizing: border-box;
  position: relative;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  
  &.user {
    background: #ffffff;
    border: 1px solid rgba(0, 0, 0, 0.05);
    color: #333;
    margin-left: auto;
  }

  &.assistant {
    background: #f8f9fa;
    border: 1px solid rgba(0, 0, 0, 0.05);
    color: #333;
    margin-right: auto;
  }

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
    transform: translateY(-1px) scaleX(1.02);
    &::before {
      opacity: 1;
      transform: scale(1.1);
    }
  }

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    border-radius: 20px;
    background: radial-gradient(circle, rgba(0, 179, 255, 0.05) 10%, transparent 10.01%);
    transform: scale(0.9);
    opacity: 0;
    transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
    pointer-events: none;
    z-index: -1;
  }
}

@media (max-width: 768px) {
  .message-content {
    max-width: 90%;
    padding: 14px 18px;
    font-size: 14px;
  }
}

.copy-indicator {
  position: absolute;
  bottom: -20px;
  right: 0;
  font-size: 12px;
  color: #666;
}

.action-buttons {
  position: absolute;
  top: 8px;
  right: 8px;
}

.refresh-icon {
  cursor: pointer;
  color: #666;
  transition: color 0.2s;
}

.refresh-icon:hover {
  color: #ceffef;
}

.input-area {
  padding: 16px;
  border-top: 1px solid rgba(0, 0, 0, 0.05);
  display: flex;
  gap: 8px;
}

.input-area .el-input {
  flex: 1;
}

.input-area .el-input ::v-deep(.el-input__inner) {
  border-radius: 12px;
  padding: 14px 16px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  line-height: 1.6;
  background: #fff;
}

.send-button {
  background: #00b3ff;
  border: 1px solid rgba(0, 0, 0, 0.1);
  color: #fff;
  border-radius: 12px;
}

.send-button:hover {
  opacity: 0.9;
}

.resize-handle {
  position: absolute;
  left: -4px;
  top: 0;
  bottom: 0;
  width: 8px;
  cursor: ew-resize;
  z-index: 1;
  transition: background 0.2s;
}

.resize-handle:hover,
.resize-handle.active {
  background: rgba(168, 168, 168, 0.2);
}

@media (max-width: 768px) {
  .resize-handle {
    display: none;
  }

  .chat-drawer {
    width: 100% !important;
  }
}

.code-block {
  margin: 12px 0;
}

.task-item {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 8px 0;
  padding: 4px 0;
}

.task-item input {
  margin: 0;
  cursor: pointer;
}

.task-item span {
  flex: 1;
}

.code-block {
  position: relative;
  margin: 20px 0;
  background: #1e1e1e;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3);
  }

  pre {
    margin: 0;
    padding: 16px;
    overflow-x: auto;
    background: #1e1e1e;
    border-radius: 0 0 12px 12px;
  }

  .code-header {
    padding: 12px 16px;
    background: rgba(255, 255, 255, 0.05);
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .lang-tag {
    font-size: 12px;
    color: rgba(255, 255, 255, 0.7);
    background: rgba(255, 255, 255, 0.1);
    padding: 4px 8px;
    border-radius: 4px;
  }

  .code-actions {
    display: flex;
    gap: 8px;
  }
}

.code-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.05);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.lang-tag {
  font-size: 12px;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  color: rgba(255, 255, 255, 0.7);
  background: rgba(255, 255, 255, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
}

.code-actions {
  display: flex;
  gap: 8px;
}

.copy-btn,
.toggle-btn {
  cursor: pointer;
  color: rgba(255, 255, 255, 0.7);
  transition: all 0.2s;
  padding: 4px;
  border-radius: 4px;
}

.copy-btn:hover,
.toggle-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
}

.copy-btn:active {
  transform: scale(0.95);
}

.copy-success {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s;
}

.copy-success.show {
  opacity: 1;
}

.numbered-item {
  display: flex;
  align-items: baseline;
  gap: 8px;
  margin: 8px 0;
}

.numbered-item .number {
  font-weight: bold;
  color: #ceffef;
  padding: 0px 5px;
}

.numbered-item .text {
  flex: 1;
}

/* Dark theme for code blocks */
.code-block pre {
  background: #1e1e1e;
  color: #d4d4d4;
}

.code-block pre code {
  color: #d4d4d4;
}

.code-block pre code .line::before {
  color: rgba(255, 255, 255, 0.3);
}

.code-header {
  background: rgba(255, 255, 255, 0.05);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.code-header .lang-tag {
  background: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.8);
}

.code-header .copy-btn {
  background: rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.8);
}

.code-header .copy-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

.code-block .toggle-btn {
  background: rgba(255, 255, 255, 0.05);
  color: rgba(255, 255, 255, 0.8);
}

.code-block .toggle-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.code-block:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
  border-color: rgba(0, 0, 0, 0.15);
}

.code-block pre {
  background: rgba(255, 255, 255, 0.8);
  border-radius: 0 0 12px 12px;
}

.code-block {
  position: relative;
  margin: 16px 0;
  background: #1e1e1e;
  border-radius: 12px;
  overflow: hidden;
  transition: all 0.2s ease;
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.code-block:hover {
  transform: translateY(-2px) scaleX(1.02);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3);
  &::before {
    opacity: 1;
    transform: scale(1.1);
  }
}

.code-block::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  border-radius: 12px;
  background: radial-gradient(circle, rgba(0, 179, 255, 0.05) 10%, transparent 10.01%);
  transform: scale(0.9);
  opacity: 0;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  pointer-events: none;
  z-index: -1;
}

.code-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.05);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.lang-tag {
  font-size: 12px;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  color: rgba(255, 255, 255, 0.7);
  background: rgba(255, 255, 255, 0.1);
  padding: 2px 6px;
  border-radius: 4px;
}

.code-actions {
  display: flex;
  gap: 8px;
}

.copy-btn,
.toggle-btn {
  cursor: pointer;
  color: rgba(255, 255, 255, 0.7);
  transition: all 0.2s;
  padding: 4px;
  border-radius: 4px;
}

.copy-btn:hover,
.toggle-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #fff;
}

.copy-btn:active {
  transform: scale(0.95);
}

.code-block pre {
  margin: 0;
  padding: 16px 16px 16px 48px;
  overflow-x: auto;
  white-space: pre;
  word-wrap: normal;
  max-height: 400px;
  overflow-y: auto;
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.1) transparent;
  counter-reset: line;
  transition: all 0.3s ease;
  position: relative;
  background: #1e1e1e;
}

.code-block.collapsed pre {
  max-height: 200px;
  overflow: hidden;
}

.code-block.collapsed::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 40px;
  background: linear-gradient(to bottom, rgba(30, 30, 30, 0) 0%, rgba(30, 30, 30, 1) 100%);
  pointer-events: none;
}

.toggle-btn {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 8px;
  text-align: center;
  background: rgba(255, 255, 255, 0.05);
  cursor: pointer;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.toggle-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.toggle-btn::after {
  content: '▼';
  font-size: 10px;
  transition: transform 0.2s;
}

.code-block.collapsed .toggle-btn::after {
  transform: rotate(180deg);
}

@media (max-width: 768px) {
  .code-block {
    margin: 8px 0;
    border-radius: 8px;
  }

  .code-block pre {
    padding: 8px 8px 8px 32px;
    font-size: 12px;
    max-height: 200px;
  }

  .code-block.collapsed pre {
    max-height: 100px;
  }

  .code-header {
    padding: 6px;
    gap: 4px;
  }

  .lang-tag {
    font-size: 11px;
    padding: 2px 6px;
  }

  .copy-btn,
  .toggle-btn {
    font-size: 11px;
    padding: 2px 6px;
  }

  .code-block:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  }
}

.code-block pre code {
  display: block;
}

.code-block pre code .line {
  display: block;
  counter-increment: line;
  position: relative;
  padding-left: 16px;
}

.code-block pre code .line::before {
  content: counter(line);
  display: inline-block;
  width: 32px;
  margin-left: -48px;
  padding-right: 16px;
  color: rgba(255, 255, 255, 0.3);
  text-align: right;
  user-select: none;
}

.code-block pre code .line:hover {
  background-color: rgba(255, 255, 255, 0.05);
}

.code-block pre code .line:hover::before {
  color: rgba(255, 255, 255, 0.6);
}

.code-block .copy-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  padding: 4px 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  color: rgba(255, 255, 255, 0.8);
  cursor: pointer;
  transition: all 0.2s;
  z-index: 2;
}

.code-block .copy-btn:hover {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
}

.code-block .copy-btn:active {
  transform: scale(0.95);
}

.code-block .copy-success {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s;
  z-index: 3;
}

.code-block .copy-success.show {
  opacity: 1;
}

@media (max-width: 768px) {
  .code-block pre {
    padding: 8px 8px 8px 32px;
    font-size: 12px;
  }

  .code-block pre code .line::before {
    width: 24px;
    margin-left: -32px;
    padding-right: 8px;
    font-size: 10px;
  }

  .code-block .copy-btn {
    padding: 2px 6px;
    font-size: 12px;
  }
}

.code-block pre code {
  font-family: 'Fira Code', 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 14px;
  line-height: 1.5;
  color: #d4d4d4;
}

.code-block pre code .hljs {
  background: transparent;
}

.code-block pre code .hljs-keyword {
  color: #569cd6;
}

.code-block pre code .hljs-string {
  color: #ce9178;
}

.code-block pre code .hljs-number {
  color: #b5cea8;
}

.code-block pre code .hljs-comment {
  color: #6a9955;
}

.code-block pre code .hljs-title {
  color: #4ec9b0;
}

.code-block pre code .hljs-params {
  color: #9cdcfe;
}

.code-block pre code .hljs-built_in {
  color: #dcdcaa;
}

.code-block pre code .hljs-literal {
  color: #569cd6;
}

.code-block pre code .hljs-type {
  color: #4ec9b0;
}

.code-block pre code .hljs-function {
  color: #dcdcaa;
}

.code-block pre code .hljs-attr {
  color: #9cdcfe;
}

.code-block pre code .hljs-variable {
  color: #9cdcfe;
}

.code-block pre code .hljs-selector-class {
  color: #d7ba7d;
}

.code-block pre code .hljs-selector-id {
  color: #d7ba7d;
}

.code-block pre code .hljs-tag {
  color: #569cd6;
}

.code-block pre code .hljs-meta {
  color: #9cdcfe;
}

.code-block pre code .hljs-section {
  color: #d7ba7d;
}

.code-block pre code .hljs-name {
  color: #569cd6;
}

.code-block pre code .hljs-attribute {
  color: #9cdcfe;
}

.code-block pre code .hljs-symbol {
  color: #569cd6;
}

.code-block pre code .hljs-bullet {
  color: #569cd6;
}

.code-block pre code .hljs-link {
  color: #569cd6;
}

.code-block pre code .hljs-emphasis {
  font-style: italic;
}

.code-block pre code .hljs-strong {
  font-weight: bold;
}

.code-block pre code .hljs-deletion {
  color: #ce9178;
}

.code-block pre code .hljs-addition {
  color: #b5cea8;
}

.code-block pre code .hljs-quote {
  color: #6a9955;
}

.code-block pre code .hljs-selector-tag {
  color: #569cd6;
}

.code-block pre code .hljs-selector-attr {
  color: #9cdcfe;
}

.code-block pre code .hljs-selector-pseudo {
  color: #569cd6;
}

.code-block pre code .hljs-template-tag {
  color: #569cd6;
}

.code-block pre code .hljs-template-variable {
  color: #9cdcfe;
}

.code-block pre code .hljs-doctag {
  color: #6a9955;
}

.code-block pre code .hljs-meta-keyword {
  color: #569cd6;
}

.code-block pre code .hljs-meta-string {
  color: #ce9178;
}

.code-block pre code {
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
  font-size: 14px;
  line-height: 1.5;
  color: #24292e;
}

.code-block pre code .line {
  transition: background-color 0.2s ease;
}

.code-block pre code .line:hover {
  background-color: rgba(16, 185, 129, 0.05);
}

.code-block pre::-webkit-scrollbar {
  width: 6px;
  height: 6px;
}

.code-block pre::-webkit-scrollbar-thumb {
  background: rgba(0, 0, 0, 0.1);
  border-radius: 3px;
}

.code-block pre::-webkit-scrollbar-track {
  background: transparent;
}

.code-block.collapsed pre {
  max-height: 200px;
  overflow: hidden;
}

.code-block.collapsed pre::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 40px;
  background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.9) 100%);
  pointer-events: none;
}

.code-block pre code {
  display: block;
}

.code-block pre code .line {
  display: block;
  counter-increment: line;
}

.code-block pre code .line::before {
  content: counter(line);
  display: inline-block;
  width: 32px;
  margin-left: -48px;
  padding-right: 16px;
  color: rgba(0, 0, 0, 0.3);
  text-align: right;
  user-select: none;
}

.code-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px;
  background: rgba(0, 0, 0, 0.05);
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.code-header .lang-tag {
  padding: 4px 8px;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.6);
  user-select: none;
}

.code-header .copy-btn {
  padding: 4px 8px;
  background: rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.6);
  cursor: pointer;
  transition: all 0.2s;
  margin-left: 8px;
}

.code-header .copy-btn {
  position: relative;
  overflow: hidden;
}

.code-header .copy-btn::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  transform: translate(-50%, -50%);
  transition: width 0.3s ease, height 0.3s ease;
}

.code-header .copy-btn:active::after {
  width: 200%;
  height: 200%;
}

.code-header .copy-btn:hover {
  background: rgba(0, 0, 0, 0.2);
}

.code-block .copy-btn:hover {
  background: rgba(0, 0, 0, 0.2);
}

.code-block .copy-success {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.2s;
}

.code-block .copy-success.show {
  opacity: 1;
}

.refresh-area {
  position: absolute;
  right: 16px;
  bottom: 16px;
  z-index: 1;
}

.refresh-button {
  padding: 8px 12px;
  border-radius: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  color: #ceffef;
  transition: all 0.2s;
}

.refresh-button:hover {
  background: rgba(16, 185, 129, 0.1);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
}

.refresh-button i {
  margin-right: 4px;
}

@media (max-width: 768px) {
  .refresh-area {
    right: 8px;
    bottom: 8px;
  }

  .refresh-button {
    padding: 6px 10px;
    font-size: 14px;
  }
}

.code-block .toggle-btn {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 8px;
  text-align: center;
  background: rgba(0, 0, 0, 0.05);
  cursor: pointer;
  font-size: 12px;
  color: rgba(0, 0, 0, 0.6);
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}

.code-block .toggle-btn:hover {
  background: rgba(0, 0, 0, 0.1);
}

.code-block .toggle-btn::after {
  content: '▼';
  font-size: 10px;
  transition: transform 0.2s;
}

.code-block.collapsed .toggle-btn::after {
  transform: rotate(180deg);
}

@media (max-width: 768px) {
  .code-block {
    margin: 8px 0;
    border-radius: 8px;
    border-width: 1px;
  }

  .code-block pre {
    padding: 8px 8px 8px 32px;
    font-size: 12px;
    max-height: 200px;
  }

  .code-block pre code .line::before {
    width: 24px;
    margin-left: -32px;
    padding-right: 8px;
    font-size: 10px;
  }

  .code-block.collapsed pre {
    max-height: 100px;
  }

  .code-header {
    padding: 6px;
    gap: 4px;
  }

  .code-header .lang-tag {
    font-size: 11px;
    padding: 2px 6px;
  }

  .code-header .copy-btn {
    font-size: 11px;
    padding: 2px 6px;
  }

  .code-block .toggle-btn {
    padding: 6px;
    font-size: 11px;
  }

  .code-block:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
  }
}

.math {
  display: inline-block;
  padding: 2px 4px;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  font-family: monospace;
}

.table-container {
  overflow-x: auto;
  margin: 12px 0;
}

.table-container table {
  width: 100%;
  border-collapse: collapse;
}

.table-container th,
.table-container td {
  padding: 8px;
  border: 1px solid rgba(0, 0, 0, 0.1);
}

.table-container th {
  background: rgba(0, 0, 0, 0.05);
  font-weight: bold;
}
</style>
